<template>
  <div class="live-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="直播" left-arrow @click-left="router.back()">
      <template #right>
        <van-icon name="search" size="18" @click="onSearch" />
      </template>
    </van-nav-bar>

    <!-- 分类标签页 -->
    <van-tabs v-model:active="activeTab" sticky swipeable>
      <van-tab title="推荐">
        <me-scroll
          ref="meScrollRef"
          v-bind="meScrollOptions"
          @init="onMeScrollInit"
          @down-callback="downCallback"
          @up-callback="upCallback"
        >
          <div class="live-grid">
            <live-card
              v-for="item in list"
              :key="item.id"
              :live="item"
              @click="handleVideoClick(item)"
            />
          </div>
        </me-scroll>
      </van-tab>
      <van-tab title="附近">
        <div class="empty-tip">
          <van-empty description="暂无附近直播" />
        </div>
      </van-tab>
      <van-tab title="分类">
        <div class="category-grid">
          <van-grid :column-num="4" :border="false">
            <van-grid-item
              v-for="category in categories"
              :key="category.id"
              :icon="category.icon"
              :text="category.name"
              @click="onCategoryClick(category)"
            />
          </van-grid>
        </div>
      </van-tab>
    </van-tabs>

    <!-- 视频弹窗 -->
    <van-popup
      v-model:show="showVideoPopup"
      position="bottom"
      :style="{ height: '75%' }"
      round
      closeable
      @close="onCloseVideo"
    >
      <div class="video-popup">
        <div class="video-container">
          <VideoPlayer
            v-if="currentVideo"
            :src="currentVideo.url"
            :type="currentVideo.type"
            :options="{
              fluid: true,
              aspectRatio: '16:9',
              autoplay: true,
              liveui: currentVideo.type === 'live',
              controlBar: {
                volumePanel: { inline: false },
                progressControl: currentVideo.type !== 'live',
              },
            }"
          />
        </div>
        <div v-if="currentVideo" class="video-info">
          <div class="title">{{ currentVideo.title }}</div>
          <div class="uploader">
            <van-image :src="currentVideo.avatar" round width="32" height="32" />
            <div class="uploader-info">
              <div class="name">{{ currentVideo.uploader }}</div>
              <div class="views">{{ formatViewCount(currentVideo.views) }}</div>
            </div>
          </div>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import LiveCard from '@/components/LiveCard.vue'
import MeScroll from '@/components/common/MeScroll.vue'
import useMeScroll from '@/hooks/useMeScroll'
import { getLiveList } from '@/api/video'
import type { LiveItem, Category } from '@/types/video'
import VideoPlayer from '@/components/VideoPlayer/index.vue'
import { formatNumber } from '@/utils/format'

// 使用 useMeScroll hook
const { meScrollRef, list, meScrollOptions, downCallback, upCallback } = useMeScroll<LiveItem>({
  requestData: async (params) => {
    const res = await getLiveList(params)
    return {
      list: res.data.list,
      total: res.data.total,
    }
  },
  params: { pageSize: 10 },
})

const router = useRouter()
const activeTab = ref(0)

// 分类数据
const categories: Category[] = [
  { id: 1, name: '游戏', icon: 'video-o' },
  { id: 2, name: '音乐', icon: 'music-o' },
  { id: 3, name: '舞蹈', icon: 'tv-o' },
  { id: 4, name: '知识', icon: 'notes-o' },
  { id: 5, name: '生活', icon: 'like-o' },
  { id: 6, name: '美食', icon: 'shop-o' },
  { id: 7, name: '动物', icon: 'photo-o' },
  { id: 8, name: '更多', icon: 'apps-o' },
]

// 当前选中的分类
const currentCategory = ref<string>('')

// 视频弹窗相关
const showVideoPopup = ref(false)
const currentVideo = ref<LiveItem | null>(null)

// 格式化观看次数
const formatViewCount = (views: number) => {
  return `${formatNumber(views)}次观看`
}

// MeScroll 初始化回调
const onMeScrollInit = (mescroll: any) => {
  console.log('MeScroll initialized:', mescroll)
}

// 点击视频卡片
const handleVideoClick = (video: LiveItem) => {
  currentVideo.value = video
  showVideoPopup.value = true
}

// 关闭视频弹窗
const onCloseVideo = () => {
  showVideoPopup.value = false
  currentVideo.value = null
}

// 点击分类
const onCategoryClick = (category: Category) => {
  currentCategory.value = category.name
  if (meScrollRef.value) {
    list.value = []
    meScrollRef.value.resetUpScroll()
  }
}

// 搜索
const onSearch = () => {
  router.push('/search')
}
</script>

<style scoped lang="less">
.live-page {
  min-height: 100vh;
  background: #f8f8f8;

  .live-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
    padding: 8px;
  }

  .empty-tip {
    padding: 40px 0;
  }

  .category-grid {
    padding: 16px;
    background: #fff;
  }

  :deep(.van-grid-item__content) {
    padding: 16px 8px;

    .van-icon {
      font-size: 28px;
      color: #666;
    }
  }

  :deep(.van-tabs__wrap) {
    background: #fff;
  }

  .video-popup {
    height: 100%;
    display: flex;
    flex-direction: column;
    padding-top: 46px; // 为关闭按钮留出空间

    .video-container {
      width: 100%;
      background: #000;
    }

    .video-info {
      padding: 16px;
      flex: 1;
      overflow-y: auto;

      .title {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 16px;
        line-height: 1.4;
      }

      .uploader {
        display: flex;
        align-items: center;
        gap: 12px;

        .uploader-info {
          flex: 1;

          .name {
            font-size: 14px;
            color: #333;
            margin-bottom: 4px;
          }

          .views {
            font-size: 12px;
            color: #666;
          }
        }
      }
    }
  }
}
</style>
